<?php

namespace app\api\controller\User;

use think\Controller;
use think\Request;

class Auth extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');
    }
    public function login()
    {
        $code = $this->request->param('code');

        $code2session = $this->code2session($code);

        $openid = isset($code2session['openid']) ? $code2session['openid'] : '';

        if(empty($openid))
        {
            $this->error('获取凭证失败');
        }

        $User = model('User.User')->where(['openid' => $openid])->find();

        if(!$User)
        {
            $this->error('您未绑定账号，请先绑定','/pages/bind/bind');
        }

        $data = [
            'id' => $User['id'],
            'email' => $User['email'],
            'nickname' => $User['nickname'],
            'avatar_cdn' => $User['avatar_cdn'],
            'sex' => $User['sex'],
            'sex_text' => $User['sex_text'],
            'province' => $User['province'],
            'city' => $User['city'],
            'district' => $User['district'],
            'createtime' => $User['createtime'],
            'content' => $User['content'],
            'point' => $User['point'],
            'vip' => $User['vip'],
            'auth' => $User['auth'],
            'cover_cdn' => $User['cover_cdn'],
            'region_text' => $User['region_text']
        ];

        $this->success('登录成功',null,$data);

    }

    public function bind()
    {
        $code = $this->request->param('code');

        $email = $this->request->param('email');

        $password = $this->request->param('password');

        if(!$code)
        {
            $this->error('授权失败');
        }

        $code2session = $this->code2session($code);

        $openid = isset($code2session['openid']) ? $code2session['openid'] : '';

        if(empty($openid))
        {
            $this->error('获取凭证失败');
        }

        $User = model('User.User')->where(['email' => $email])->find();

        if($User)
        {
            $password = md5($password.$User['salt']);

            if($password != $User['password'])
            {
                $this->error('密码错误');
            }

            $data = [
                'id' => $User['id'],
                'openid' => $openid
            ];

            $result = model('User.User')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error('绑定失败');
            }else{
                $UserData = [
                    'id' => $User['id'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar_cdn' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'sex_text' => $User['sex_text'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover_cdn' => $User['cover_cdn'],
                    'region_text' => $User['region_text']
                ];

                $this->success('绑定成功',null,$UserData);            
            }

        }else{
            // 密码盐
            $salt = build_ranstr();

            $password = md5($password.$salt);

            $point = model('Config')->where(['key' => 'RegisterPoint'])->value('value');


            $data = [
                'email' => $email,
                'password' => $password,
                'salt' => $salt,
                'openid' =>$openid,
                'point' => $point,
                'vip' => 1,
                'auth' => 0,
                'sex' => 0
            ];

            $result = $this->UserModel->validate('common/User/User.vue')->save($data);

            if($result === FALSE)
            {
                $this->error($this->UserModel->getError());
            }else{
                $User = $this->UserModel->find($this->UserModel->id);

                $UserData = [
                    'id' => $User['id'],
                    'email' => $User['email'],
                    'nickname' => $User['nickname'],
                    'avatar_cdn' => $User['avatar_cdn'],
                    'sex' => $User['sex'],
                    'sex_text' => $User['sex_text'],
                    'province' => $User['province'],
                    'city' => $User['city'],
                    'district' => $User['district'],
                    'createtime' => $User['createtime'],
                    'content' => $User['content'],
                    'point' => $User['point'],
                    'vip' => $User['vip'],
                    'auth' => $User['auth'],
                    'cover_cdn' => $User['cover_cdn'],
                    'region_text' => $User['region_text']
                ];

                $this->success('绑定成功',null,$UserData);
            }
        }
    }

    public function profile()
    {
        $userid = $this->request->param('userid');

        $params = $this->request->param();
        
        $user = $this->UserModel->find($userid);

        if(!$user)
        {
            $this->error('用户不存在,请重新绑定账号');
        }

        $data = [
            'id' => $userid,
            'nickname' => $params['nickname'],
            'sex' => $params['sex'],
            'content' => $params['content']
        ];

        if(!empty($params['code']))
        {
            $region = model('Region')->where(['code' => $params['code']])->value('parentpath');

            if(!$region)
            {
                $this->error('所选地区不存在,请重新选择');
            }

            [$province,$city,$district] = explode(',',$region);

            $data['province'] = $province;
            $data['city'] = $city;
            $data['district'] = $district;
        }

        if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
        {
            $cover = upload('cover');

            if($cover['code'] == 0)
            {
                $this->error($cover['msg']);
            }

            $data['cover'] = $cover['data'];
        }

        $result = $this->UserModel->isUpdate(true)->save($data);

        if($result === FALSE)
        {
            if(!empty($data['cover']) && $_FILES['cover']['size'] > 0)
            {
                @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
            }

            $this->error('修改失败');
        }else{
            if(!empty($data['cover']) && $_FILES['cover']['size'] > 0)
            {
                @is_file('.' . $user['cover']) && unlink('.' . $user['cover']);
            }

            $User = $this->UserModel->find($userid);

            $UserData = [
                'id' => $User['id'],
                'email' => $User['email'],
                'nickname' => $User['nickname'],
                'avatar_cdn' => $User['avatar_cdn'],
                'sex' => $User['sex'],
                'sex_text' => $User['sex_text'],
                'province' => $User['province'],
                'city' => $User['city'],
                'district' => $User['district'],
                'createtime' => $User['createtime'],
                'content' => $User['content'],
                'point' => $User['point'],
                'vip' => $User['vip'],
                'auth' => $User['auth'],
                'cover_cdn' => $User['cover_cdn'],
                'region_text' => $User['region_text']
            ];

            $this->success('修改成功',null,$UserData);

        }



    }

    protected function code2session($code)
    {
        // config.php => 配置一个appid和密钥
        $appid = 'wx07f840600e4acc3d';
        $secret = '0670334c41bbbcaf4679c692e9dbb4b8';

        $ApiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        $result = $this->https_request($ApiUrl);

        $result = json_decode($result,true);

        if(!$result)
        {
            return false;
        }else{
            return $result;
        }
    }

    private function https_request($url,$data = null)
    {
        if(function_exists('curl_init')){
        $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
}
